using FeishuWorkflowService.Models;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;

namespace FeishuWorkflowService.Services
{
    public class WorkflowService : IWorkflowService
    {
        private readonly IFeishuService _feishuService;
        private readonly HttpClient _httpClient;
        private readonly ILogger<WorkflowService> _logger;
        private readonly ServiceConfig _serviceConfig;

        public WorkflowService(
            IFeishuService feishuService,
            HttpClient httpClient,
            ILogger<WorkflowService> logger,
            IOptions<ServiceConfig> serviceConfig)
        {
            _feishuService = feishuService;
            _httpClient = httpClient;
            _logger = logger;
            _serviceConfig = serviceConfig.Value;
        }

        /// <summary>
        /// 触发飞书审批流程
        /// </summary>
        public async Task<string> TriggerWorkflowAsync(TriggerWorkflowRequest request)
        {
            try
            {
                _logger.LogInformation("开始触发飞书审批流程: {RequestData}", JsonConvert.SerializeObject(request));

                // 构建飞书审批流程请求
                var workflowRequest = new CreateWorkflowRequest
                {
                    ApprovalCode = request.ApprovalCode,
                    OperatorId = request.OperatorId,
                    ApproverUserIds = request.ApproverUserIds,
                    FormData = request.FormData
                };

                // 调用飞书服务创建审批流程
                var instanceId = await _feishuService.CreateWorkflowInstanceAsync(workflowRequest);
                _logger.LogInformation("成功触发飞书审批流程，实例ID: {InstanceId}", instanceId);

                return instanceId;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "触发飞书审批流程异常");
                throw;
            }
        }

        /// <summary>
        /// 处理飞书审批回调
        /// </summary>
        public async Task<bool> HandleWorkflowCallbackAsync(WorkflowCallbackData callbackData)
        {
            try
            {
                _logger.LogInformation("收到飞书审批回调: {CallbackData}", JsonConvert.SerializeObject(callbackData));

                // 判断审批状态
                if (callbackData.Event.InstanceId != null && 
                    callbackData.Event.ApprovalStatus == "APPROVED")
                {
                    // 审批通过，执行后续业务逻辑
                    _logger.LogInformation("审批已通过，执行后续业务逻辑，实例ID: {InstanceId}", callbackData.Event.InstanceId);
                    return await ExecuteApprovalPassedActionAsync(callbackData.Event.InstanceId);
                }
                else if (callbackData.Event.ApprovalStatus == "REJECTED")
                {
                    // 审批拒绝，记录日志
                    _logger.LogInformation("审批已拒绝，实例ID: {InstanceId}", callbackData.Event.InstanceId);
                    return true; // 回调处理成功
                }
                else
                {
                    // 其他状态，记录日志
                    _logger.LogInformation("审批状态更新: {Status}，实例ID: {InstanceId}", 
                        callbackData.Event.ApprovalStatus, callbackData.Event.InstanceId);
                    return true; // 回调处理成功
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理飞书审批回调异常");
                return false; // 回调处理失败
            }
        }

        /// <summary>
        /// 执行审批通过后的业务逻辑
        /// </summary>
        public async Task<bool> ExecuteApprovalPassedActionAsync(string instanceId)
        {
            try
            {
                // 获取审批流程详情
                var workflowStatus = await _feishuService.GetWorkflowStatusAsync(instanceId);
                _logger.LogInformation("获取审批流程详情成功: {WorkflowStatus}", JsonConvert.SerializeObject(workflowStatus));

                // 调用业务系统API
                var requestUrl = $"{_serviceConfig.ApiBaseUrl}/api/business/approval-passed";
                var requestBody = new
                {
                    instanceId = workflowStatus.InstanceId,
                    approvalCode = workflowStatus.ApprovalCode,
                    title = workflowStatus.Title,
                    formData = workflowStatus.FormData
                };

                // 设置请求头
                _httpClient.DefaultRequestHeaders.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                _httpClient.DefaultRequestHeaders.Add("X-API-Key", _serviceConfig.ApiKey);

                // 发送请求
                var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync(requestUrl, content);

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    _logger.LogInformation("调用业务系统API成功: {Response}", responseContent);
                    return true;
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    _logger.LogError("调用业务系统API失败: {StatusCode}, {Response}", response.StatusCode, errorContent);
                    return false;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行审批通过后的业务逻辑异常");
                return false;
            }
        }
    }
}